package com.seeyon.apps.shangqi.wfe;


import com.kingdee.bos.webapi.sdk.K3CloudApi;

import com.seeyon.apps.shangqi.util.PJshangqi;

import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.workflow.event.AbstractWorkflowEvent;
import com.seeyon.ctp.workflow.event.WorkflowEventData;
import com.seeyon.ctp.workflow.event.WorkflowEventResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.*;


public class FLBXWfe extends AbstractWorkflowEvent {
    private static Log log = LogFactory.getLog(FLBXWfe.class);


    //private EnumManager enumManagerNew;
    static EnumManager enumManagerNew = (EnumManager) AppContext.getBean("enumManagerNew");

    private static CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager");

    public void setOrgManager(OrgManager orgManager) {
        this.orgManager = orgManager;
    }

    private OrgManager orgManager;


    static K3CloudApi api = new K3CloudApi();

    @Override
    public String getId() {
        return "flbxWfe";
    }

    @Override
    public String getLabel() {
        return "金蝶系统_费用报销";
    }


    @Override
    public ApplicationCategoryEnum getAppName() {
        return ApplicationCategoryEnum.form;
    }


    @Override
    public WorkflowEventResult onBeforeFinishWorkitem(WorkflowEventData data) {

        WorkflowEventResult wfe = new WorkflowEventResult();
        String resultFk = importPayCost(data);
        wfe.setAlertMessage(resultFk);
        return wfe;
    }

    public String importPayCost(WorkflowEventData data) {
        try {
            Map<String, Object> paramsMap = data.getBusinessData();
            // long summaryId = data.getSummaryId();
            Object formDataBean = paramsMap.get("formDataBean");


            Map<Object, Object> jiefang = new HashMap<>();
            Map<Object, Object> daifangfang = new HashMap<>();
            String sp_formdatabean = formDataBean.toString().substring(0 + 3, formDataBean.toString().length());
            String templateCode = "FYSQD";
            String summary = sp_formdatabean + "_" + templateCode;
            log.info("给第三方的参数为:" + summary);
            List<Map<Object, Object>> minxi = new ArrayList<>();
            //明细数据
            List minxi_code = (List) paramsMap.get("科目编码");
            List minxi_name = (List) paramsMap.get("科目名称");
            List minxi_num = (List) paramsMap.get("发票币种");
            List minxi_moeny = (List) paramsMap.get("报销金额.发票原币");
            List minxi_moenygb = (List) paramsMap.get("费用报销金额_港币");
            List minxi_jfzy = (List) paramsMap.get("借方摘要");
            //   List minxi_yuanbi = (List) paramsMap.get("（合计/申请）金额（原币）");
            if (0 != minxi_name.size()) {
                for (int i = 0; i < minxi_name.size(); i++) {
                    String code = minxi_code.get(i).toString();
                    Map<Object, Object> minxi_map = new HashMap<>();
                    if (!code.contains(".") && code.length() > 4) {
                        code = PJshangqi.getcode(code);
                    }
                    minxi_map.put("minxi_code", code);
                    minxi_map.put("minxi_name", minxi_name.get(i));
                    //币种
                    Object num = minxi_num.get(i);
                    String minxi_fp_enumItemCode = enumManagerNew.getEnumItem(Long.valueOf(num.toString())).getEnumItemCode();
                    minxi_map.put("minxi_num", minxi_fp_enumItemCode);
                    minxi_map.put("minxi_moeny", minxi_moeny.get(i));
                    minxi_map.put("minxi_jfzy", minxi_jfzy.get(i));
                    minxi_map.put("minxi_moenygb", minxi_moenygb.get(i));
                    //   minxi_map.put("minxi_yuanbi", minxi_yuanbi.get(i));
                    minxi.add(minxi_map);
                }
            }
            //jiefang数据
            BigDecimal df_money = (BigDecimal) paramsMap.get("付款金额-原币");
            BigDecimal df_money_benwei = (BigDecimal) paramsMap.get("付款金额-本位币");
            BigDecimal df_hl = (BigDecimal) paramsMap.get("收款币种对港币汇率");
            //原币
            Long df_yb = (Long) paramsMap.get("币种-收款");
            String df_yb_enumItemCode = enumManagerNew.getEnumItem(df_yb).getEnumItemCode();
            String df_yb_enumItemCode1 = enumManagerNew.getEnumItem(df_yb).getEnumvalue();
            //本位币
            Long df_bwb = (Long) paramsMap.get("收款币种");

            String df_bwb_enumItemCode = enumManagerNew.getEnumItem(df_bwb).getEnumItemCode();
            String jf_sqrcode = (String) paramsMap.get("申请人编码");
            String df_bank = (String) paramsMap.get("银行科目编号");
            //   String df_bank = (String) paramsMap.get("付款银行编码");
            //获取时间转换
            Date df_paydate = (Date) paramsMap.get("付款日期");
            SimpleDateFormat dateformat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String a1 = dateformat1.format(df_paydate);


            String jf_depcode = (String) paramsMap.get("部门编码");
            String df_orgcode = (String) paramsMap.get("组织机构编码");
            String jf_oacode = (String) paramsMap.get("表单编号");
            //贷方摘要组合
            String df_dfzy = (String) paramsMap.get("贷方摘要");
            //借方数据
            jiefang.put("jf_sqrcode", jf_sqrcode);
            jiefang.put("jf_depcode", jf_depcode);
            jiefang.put("jf_oacode", jf_oacode);
            jiefang.put("summary", summary);
            //贷方数据YUKB_ExpenseReimbursement
            daifangfang.put("df_money", df_money);
            daifangfang.put("df_money_benwei", df_money_benwei);
            daifangfang.put("df_bank", df_bank);
            daifangfang.put("df_paydate", a1);
            daifangfang.put("df_orgcode", df_orgcode);
            daifangfang.put("df_dfzy", df_dfzy);
            daifangfang.put("df_bwb", df_bwb_enumItemCode);
            daifangfang.put("df_yb", df_yb_enumItemCode);
            daifangfang.put("df_hl", df_hl);
            String pingjie = PJshangqi.flbxpingjie(jiefang, daifangfang, minxi);
            log.info("数据拼接为" + pingjie);
            String yukb_expenseReimbursement = api.save("YUKB_ExpenseReimbursement", pingjie);
            System.out.println(yukb_expenseReimbursement);
            JSONObject jsonObject = new JSONObject(yukb_expenseReimbursement);
            boolean isSuccess = jsonObject.getJSONObject("Result")
                    .getJSONObject("ResponseStatus")
                    .getBoolean("IsSuccess");
            // 打印结果
            if (isSuccess) {
                String Number = jsonObject.getJSONObject("Result")
                        .getString("Number");
                FormBean formBean = cap4FormManager.getFormByFormCode(templateCode);
                System.out.println("sp_formdatabean+" + sp_formdatabean);
                FormDataMasterBean formDataMasterBean = cap4FormManager.getDataMasterBeanById(Long.parseLong(sp_formdatabean), formBean, null);
                String jindiecode = formDataMasterBean.getFormTable().getFieldBeanByDisplay("金蝶单据编号").getName();
                List<String> fieldList = new ArrayList<String>();
                formDataMasterBean.addFieldValue(jindiecode, Number);
                fieldList.add(jindiecode);
                System.out.println("jindiecode+" + jindiecode);
                cap4FormManager.saveOrUpdateFormData(formDataMasterBean, formBean.getId(), true, fieldList);
                return null;
            } else {
                Object Errors = jsonObject.getJSONObject("Result")
                        .getJSONObject("ResponseStatus")
                        .get("Errors");
                return Errors.toString();

            }
        } catch (Exception e) {
            log.error("数据错误" + e.getMessage());
            return "数据报错" + e.getMessage();

        }
    }
}
